import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  DatePicker,
  Divider,
  BackTop,
} from 'antd';

import {
  isInvalid,
  formatDatetime,
  getRandomColor,
  searchFromList,
  refitCommonData,
} from '../../utils/tools';
import StandardTableCustom from '../../customComponents/StandardTableCustom';
import PageHeaderWrapperCustom from '../../customComponents/PageHeaderWrapperCustom';
import Ellipsis from '../../components/Ellipsis';

import styles from './List.less';

const FormItem = Form.Item;
const { RangePicker } = DatePicker;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

@connect(({ saler, global, loading }) => ({
  saler,
  global,
  loading: loading.models.saler,
}))
@Form.create()
class Standard extends PureComponent {
  isMountedFlag = false;

  state = {
    dataLoading: true,
    processing: false,
    formValues: {},
    customData: {
      count: 0,
      list: [],
      pagination: {},
    },
    pageNo: 1,
    pageSize: 10,
  };

  componentDidMount() {
    this.isMountedFlag = true;
    const { pageNo, pageSize } = this.state;

    this.loadData({ pageNo, pageSize });
  }

  componentWillUnmount() {
    this.isMountedFlag = false;
  }

  cityList = () => {
    const { global } = this.props;
    return refitCommonData(global.cityList, {
      key: -10000,
      name: '不限',
      flag: -10000,
    });
  };

  getCityName = (v, defaultValue = '') => {
    if (isInvalid(v)) {
      return defaultValue;
    }

    const item = searchFromList('flag', v, this.cityList());
    return item == null ? '未知' : item.name;
  };

  deliverRegionList = () => {
    const { global } = this.props;
    return refitCommonData(global.deliverRegionList, {
      key: -10000,
      name: '不限',
      flag: -10000,
    });
  };

  getDeliverRegionName = (v, defaultValue = '') => {
    if (isInvalid(v)) {
      return defaultValue;
    }

    const item = searchFromList('flag', v, this.deliverRegionList());
    return item == null ? '未知' : item.name;
  };

  salerStatusList = () => {
    const { global } = this.props;
    return refitCommonData(global.salerStatusList, {
      key: -10000,
      name: '不限',
      flag: -10000,
    });
  };

  getSalerStatusName = (v, defaultValue = '') => {
    if (isInvalid(v)) {
      return defaultValue;
    }

    const item = searchFromList('flag', v, this.salerStatusList());
    return item == null ? '未知' : item.name;
  };

  loadData = params => {
    const { dispatch } = this.props;

    const submitData = params;
    submitData.nowpageindex = submitData.pageNo;
    submitData.pagesize = submitData.pageSize;

    this.setState({ dataLoading: true });

    dispatch({
      type: 'saler/list',
      payload: submitData,
    }).then(() => {
      if (this.isMountedFlag) {
        const {
          saler: { data },
        } = this.props;

        this.setState({ customData: data, dataLoading: false });
      }
    });
  };

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    this.loadData(params);
  };

  handleFormReset = () => {
    const { form } = this.props;
    const { pageSize } = this.state;

    form.resetFields();
    this.setState({
      formValues: {},
    });

    this.loadData({ pageNo: 1, pageSize });
  };

  refreshGrid = pageNo => {
    const { customData } = this.state;
    const { pagination } = customData;

    const params = {
      pageNo: (pageNo || 1) <= 1 ? 1 : pageNo,
      pageSize: pagination.pageSize,
    };

    this.loadData(params);
  };

  handleSearch = e => {
    e.preventDefault();
    const { form } = this.props;
    const { pageSize } = this.state;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
      });

      this.loadData({
        ...values,
        pageNo: 1,
        pageSize,
      });
    });
  };

  goToEdit = record => {
    const { dispatch } = this.props;
    const { intsalerid } = record;
    const location = {
      pathname: `/person/editSaler/load/${intsalerid}/basicInfo`,
    };
    dispatch(routerRedux.push(location));
  };

  renderSimpleForm() {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    const { dataLoading } = this.state;

    const salerStatusData = this.salerStatusList();
    const salerStatusOption = [];

    salerStatusData.forEach(item => {
      const { name, flag } = item;
      salerStatusOption.push(
        <Select.Option key={flag} value={flag}>
          {name}
        </Select.Option>
      );
    });

    const deliverRegionData = this.deliverRegionList();
    const deliverRegionOption = [];

    deliverRegionData.forEach(item => {
      const { name, flag } = item;
      deliverRegionOption.push(
        <Select.Option key={flag} value={flag}>
          {name}
        </Select.Option>
      );
    });

    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }} justify="end">
          <Col md={5} sm={24}>
            <FormItem label="姓名">
              {getFieldDecorator('name')(<Input placeholder="请输入姓名" />)}
            </FormItem>
          </Col>

          <Col md={6} sm={24}>
            <FormItem label="电话">
              {getFieldDecorator('phone')(<Input placeholder="请输入联系电话" />)}
            </FormItem>
          </Col>
          <Col md={13} sm={24}>
            <FormItem label="申请时段">
              {getFieldDecorator('dateRange', {
                rules: [{ required: false, message: '请选择申请时段!' }],
              })(
                <RangePicker
                  style={{ width: '100%' }}
                  showTime={{ format: 'HH:mm' }}
                  format="YYYY-MM-DD HH:mm"
                  placeholder={['开始时间', '结束时间']}
                  onChange={this.onDateRangeChange}
                />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }} justify="end">
          <Col md={5} sm={24}>
            <FormItem label="社区">
              {getFieldDecorator('communityName')(<Input placeholder="请输入社区名称" />)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="配送">
              {getFieldDecorator('deliverRegionFlag', {
                rules: [{ required: false, message: '请选择配送区域!' }],
                initialValue: deliverRegionData[0].flag,
              })(
                <Select placeholder="请选择配送区域" style={{ width: '100%' }}>
                  {deliverRegionOption}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={5} sm={24}>
            <FormItem label="审核状态">
              {getFieldDecorator('intstate', {
                rules: [{ required: false, message: '请选择审核状态!' }],
                initialValue: salerStatusData[0].flag,
              })(
                <Select placeholder="请选择审核状态" style={{ width: '100%' }}>
                  {salerStatusOption}
                </Select>
              )}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button disabled={dataLoading} type="primary" icon="search" htmlType="submit">
                查询
              </Button>
              <Button
                disabled={dataLoading}
                style={{ marginLeft: 8 }}
                icon="reload"
                onClick={this.handleFormReset}
              >
                重置
              </Button>
              <Divider type="vertical" />
              <Button
                disabled={dataLoading}
                type="dashed"
                icon="export"
                onClick={this.showAddNewModal}
              >
                导出
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const { loading } = this.props;
    const { customData, dataLoading, processing } = this.state;
    const columns = [
      {
        title: 'Id',
        dataIndex: 'intmerchantid',
        width: 80,
        align: 'center',
      },
      {
        title: '用户Id',
        dataIndex: 'intuserid',
        width: 80,
        align: 'center',
      },
      {
        title: '城市',
        dataIndex: 'intcityid',
        width: 100,
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis tooltip lines={1}>
              {this.getCityName(val, '--')}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '服务站名',
        dataIndex: 'chvmname',
        width: 200,
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis tooltip lines={1}>
              {val}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '推荐人→站长姓名',
        dataIndex: 'invitorName',
        align: 'center',
        render: (val, record) => (
          <Fragment>
            <Ellipsis tooltip lines={1}>
              {val || '无'} → <span className={styles.salerName}>{record.chvrealname}</span>
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '周件',
        dataIndex: 'weekCount',
        width: 60,
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis tooltip lines={1}>
              {val || '--'}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '周销',
        dataIndex: 'weekSaleAmount',
        width: 60,
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis tooltip lines={1}>
              {val || '--'}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '周排',
        dataIndex: 'weekPlan',
        width: 60,
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis tooltip lines={1}>
              {val || '--'}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '月件',
        dataIndex: 'monthCount',
        width: 60,
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis tooltip lines={1}>
              {val || '--'}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '月销',
        dataIndex: 'monthSaleAmount',
        width: 60,
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis tooltip lines={1}>
              {val || '--'}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '月排',
        dataIndex: 'monthPlan',
        width: 60,
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis tooltip lines={1}>
              {val || '--'}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '段销件',
        dataIndex: 'duanXiaoJian',
        width: 80,
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis tooltip lines={1}>
              {val || '--'}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '段销额',
        dataIndex: 'duanXiaoE',
        width: 80,
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis tooltip lines={1}>
              {val || '--'}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '售后数',
        dataIndex: 'afterSaleCount',
        width: 80,
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis tooltip lines={1}>
              {val || '--'}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '退款数',
        dataIndex: 'refundCount',
        width: 80,
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis tooltip lines={1}>
              {val || '--'}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '线路',
        dataIndex: 'deliverRegionFlag',
        width: 120,
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis tooltip lines={1}>
              {this.getDeliverRegionName(val, '--')}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '状态',
        dataIndex: 'intstate',
        width: 120,
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis
              style={{
                color: getRandomColor(val + 14),
              }}
              tooltip
              lines={1}
            >
              {this.getSalerStatusName(val, '--')}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '申请时间',
        dataIndex: 'dtmintime',
        width: 120,
        align: 'center',
        sorter: false,
        render: val => (
          <Fragment>
            <Ellipsis tooltip lines={1}>
              {formatDatetime(val, 'MM-DD HH:mm', '--')}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '操作',
        width: 106,
        fixed: 'right',
        align: 'center',
        render: (text, record) => (
          <Fragment>
            <Dropdown.Button
              size="small"
              onClick={() => this.goToEdit(record)}
              overlay={
                <Menu onClick={e => this.handleMenuClick(e, record)}>
                  <Menu.Item key="1">
                    <Icon type="delete" />
                    删除
                  </Menu.Item>
                </Menu>
              }
            >
              <Icon type="edit" />
              修改
            </Dropdown.Button>
          </Fragment>
        ),
      },
    ];

    return (
      <PageHeaderWrapperCustom title="用户列表">
        <Card bordered={false} className={styles.containorBox}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <StandardTableCustom
              loading={dataLoading || processing || loading}
              data={customData}
              columns={columns}
              onChange={this.handleStandardTableChange}
              scroll={{ x: 1800 }}
            />
          </div>
        </Card>
        <BackTop />
      </PageHeaderWrapperCustom>
    );
  }
}

export default Standard;
